import './assets/main.css'

import { createApp, provide } from 'vue'
import { createPinia, storeToRefs } from 'pinia'
// 全局导入ElementPlus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// 设置语言环境
import moment from 'moment'
import 'moment/dist/locale/zh-cn'
/*禁止ios缩放，双击和双指*/
window.onload = function () {
  document.addEventListener('touchstart', function (event) {
    if (event.touches.length > 1) {
      event.preventDefault()
    }
  })
  var lastTouchEnd = 0
  document.addEventListener(
      'touchend',
      function (event) {
        var now = new Date().getTime()
        if (now - lastTouchEnd <= 300) {
          event.preventDefault()
        }
        lastTouchEnd = now
      },
      false
  )
  document.addEventListener('gesturestart', function (event) {
    event.preventDefault()
  })
}
// 注册富文本插件
import { Boot } from '@wangeditor/editor'
import attachmentModule from '@wangeditor/plugin-upload-attachment'
import linkCardModule from '@wangeditor/plugin-link-card'
// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
Boot.registerModule(attachmentModule)
// 注册。要在创建编辑器之前注册，且只能注册一次，不可重复注册。
Boot.registerModule(linkCardModule)

import App from './App.vue'
import router from '@/router'
// 导入api接口
import api from './api'
const app = createApp(App)
// 设置 moment.js 的语言
moment.locale('zh-cn')
// 导入所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.provide('api', api)
app.use(createPinia())
// 判断当前端是手机还是pc
import MobileDetect from 'mobile-detect'
let ifMobile = new MobileDetect(window.navigator.userAgent)
app.provide('ifMobile', ifMobile.mobile())
// 页面刷新恢复tab信息
import { usePageTabStore } from '@/stores/pageTab'
import { useOptionDataStore } from '@/stores/optionData'
import sessionUtil from '@/utils/session'
// 恢复路由缓存
function restoreCacheRouter() {
  const routers = JSON.parse(sessionStorage.getItem('router'))
  if (routers) {
    // 获取全部组件
    let modules = import.meta.glob('@/views/template/**/IndexView.vue')
    for (let key in routers) {
      const routerItem = routers[key]
      const addRoute = {
        path: routerItem.path,
        name: routerItem.name,
        meta: routerItem.meta
      }
      if (routerItem?.meta?.componentPath) {
        addRoute.component = modules[routerItem.meta.componentPath]
      }
      router.addRoute('homeIndex', addRoute)
    }
  }
}
// 恢复tab缓存信息
function restoreCacheTab() {
  let cachedComponents = JSON.parse(sessionStorage.getItem('cachedComponents'))
  let editableTabs = JSON.parse(sessionStorage.getItem('editableTabs'))
  let editableTabsValue = sessionStorage.getItem('editableTabsValue')
  usePageTabStore().load(editableTabs || [], editableTabsValue || '', cachedComponents || [])
}
// 恢复选项数据缓存
function restoreCacheOptionData() {
  let optionDatas = JSON.parse(sessionStorage.getItem('optionDatas'))
  let options = JSON.parse(sessionStorage.getItem('options'))
  useOptionDataStore().load(optionDatas || {}, options || [])
}
ifLogin()
restoreCacheAll()
// 刷新页面/直接访问路径时，router 未挂载时判断当前登录状态重定向到登录页
function ifLogin() {
  const member = JSON.parse(sessionStorage.getItem('member'))
  if (!member && window.location.pathname !== '/') {
    window.location.href = '/'
  }
}
// 恢复全部缓存
function restoreCacheAll() {
  restoreCacheRouter()
  restoreCacheTab()
  restoreCacheOptionData()
  console.log('缓存恢复完成')
}
// 开始监听浏览器刷新事件
window.addEventListener('beforeunload', () => {
  // 缓存路由(不会频繁刷新，已在获取菜单时缓存)
  // 缓存标签
  const { editableTabs, editableTabsValue, cachedComponents } = storeToRefs(usePageTabStore())
  sessionUtil.setItem('editableTabs', JSON.stringify(editableTabs.value))
  sessionUtil.setItem('editableTabsValue', editableTabsValue.value)
  sessionUtil.setItem('cachedComponents', JSON.stringify(cachedComponents.value))
  // 缓存选项数据
  const { optionDatas, options } = storeToRefs(useOptionDataStore())
  sessionUtil.setItem('optionDatas', JSON.stringify(optionDatas.value))
  sessionUtil.setItem('options', JSON.stringify(options.value))
  console.log('添加缓存完成')
})
// 初始化文件上传地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/FaSysFileApi/upload'
app.provide('uploadUrl', uploadUrl)
app.use(ElementPlus)
app.use(router)
app.mount('#app')
